package com.yuebao.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {
    
    public static final String Page_Form_Key="payment:page:";
    public static final String Order_History="payment:history:";
    
    private StringRedisTemplate redisTemplate;
    
    public CacheClient(StringRedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }
    
    
    
    public void set(String key, Object val, Long time, TimeUnit unit){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(val),time,unit);
    }
    public void set(String key, Object val){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(val));
    }
    
    
    public  String pageCallBack(String value){
        UUID token = UUID.randomUUID();
        redisTemplate.opsForValue().set(Page_Form_Key+token, value);
        log.info("token:{}",token);
        return String.valueOf(token);
    }
    
    public  String  readPageCallBack(String token){
        String page = redisTemplate.opsForValue().get(Page_Form_Key + token);
        return page;
    }

    public void setWithLogicalExpire(String key,Object val,Long time,TimeUnit unit){
        //涉及逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(val);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        // 写入redis
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData)); //不设置过期时间

    }
    //缓存穿透
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,Long time,TimeUnit unit){ //缓存穿透
        String key= keyPrefix + id;

        //1.从redis查缓存
        String json = (String) redisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if (StrUtil.isNotBlank(json)){
            //3.存在直接返回
            return JSONUtil.toBean(json,type);
        }
        // 命中缓存空值 "" 缓存穿透
        if (json!=null){
            return null;
        }


        //4.不存在根据id查询数据库
        R r=dbFallback.apply(id);
        //5.不存在，返回错误
        if(r==null){
            // 避免缓存穿透 把空数据也存到redis 设置过期时间避免越来越多
            redisTemplate.opsForValue().set(key,"",2L,TimeUnit.MINUTES);
            return null;
        }
        //6.存在，写入redis
//        redisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(r),30L, TimeUnit.MINUTES);
        this.set(key,r,time,unit);
        //7.返回
        return r;

    }
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallback,Long time,TimeUnit unit){ //缓存穿透
        String key= keyPrefix + id;

        //1.从redis查缓存
        String json = (String) redisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if (StrUtil.isBlank(json)){
            return null;
        }
        //命中 先把json反序列化成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data= (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime=redisData.getExpireTime();
        //判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        //已过期 缓存重建

        String lockKey=RedisConstants.LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);

        if (isLock){

                //开启独立线程 重建
                CACHE_REBUILD_EXECUTOR.submit(()->{
                    try {
                        R r1=dbFallback.apply(id);
                        this.setWithLogicalExpire(key,r1,time,unit);
                    } catch (Exception e) {
                        throw  new RuntimeException(e);
                    }finally {
                        unlock(lockKey);
                    }
                });
        }
        //7.返回
        return r;

    }
    private  static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    private boolean tryLock(String key){

        Boolean flag= redisTemplate.opsForValue().setIfAbsent(key,Thread.currentThread().getName(),10,TimeUnit.SECONDS);//setnx 实现互斥锁 设置时间 防止解锁动作挂掉产生死锁
        return BooleanUtil.isTrue(flag);

    }

    private void unlock(String key){
        redisTemplate.delete(key);
    }
    
    
    


}
